<template>
	<view class="history-container">
		<!-- 学生信息头部 -->
		<view class="student-header-card">
			<view class="header-content">
				<image class="student-avatar" :src="getAvatarUrl(currentStudent.aver)" mode="aspectFill"></image>
				<view class="header-text">
					<text class="student-name">{{currentStudent.studentName}}</text>
					<text class="student-grade">{{currentStudent.grade}}</text>
					<view class="header-title">
						<text class="title">历史分数记录</text>
						<text class="subtitle">{{currentStudent.studentName}}的学习成长轨迹</text>
					</view>
				</view>
			</view>
			<view class="header-decoration"></view>
		</view>
		<!-- 日期选择卡片 -->
		<scroll-view scroll-x class="date-scroll" :scroll-into-view="'date-'+activeDateIndex">
			<view class="date-cards">
				<view v-for="(date, index) in dateList" :key="index" :id="'date-'+index" class="date-card"
					:class="{active: activeDateIndex === index}" @click="changeDate(index)">
					<text class="day">{{ formatDay(date) }}</text>
					<text class="weekday">{{ formatWeekday(date) }}</text>
					<text class="date">{{ formatDate(date) }}</text>
				</view>
			</view>
		</scroll-view>

		<!-- 分数统计卡片 -->
		<view class="stats-container">
			<view class="stats-card">
				<view class="stat-item">
					<text class="stat-value">{{dailyTotalScores}}</text>
					<text class="stat-label">今日总得分</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{dailySubjectCount}}</text>
					<text class="stat-label">今日科目数</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{dailyMaxScoreItem.scoreName}}</text>
					<text class="stat-label">今日最高分</text>
				</view>
			</view>
		</view>

		<!-- 分数记录列表 -->
		<view class="score-list">
			<view class="score-item-container" v-for="(item, index) in filteredScores" :key="item.id">
				<!-- 删除按钮 -->
				<view class="delete-btn" v-if="item.teacherId === teacher.teacherId" @click="deleteScore(item.id)">
					<uni-icons type="trash" size="24" color="#fff"></uni-icons>
				</view>

				<!-- 分数卡片 -->
				<view class="score-item" @touchstart="touchStart($event, item.id)"
					@touchmove="touchMove($event, item.id)" @touchend="touchEnd(item.id)"
					:style="{transform: `translateX(${item.translateX || 0}px)`}">
					<view class="subject-icon" :style="{backgroundColor: getSubjectColor(item.scoreType)}">
						<text>{{getSubjectAbbr(item.scoreType)}}</text>
					</view>
					<view class="score-content">
						<view class="score-header">
							<text class="score-name">{{ item.scoreName }}</text>
							<text class="score-value">{{ item.displayScore }}</text>
						</view>
						<view class="score-detail">
							<text class="teacher-name">{{ item.teacherName || '系统记录' }}</text>
							<text class="time">{{ formatTime(item.time) }}</text>
						</view>
						<view class="score-footer">
							<text class="grade">{{ item.grade }}</text>
							<view class="tags">
								<text class="tag" v-if="item.score >= 20">优秀</text>
								<text class="tag" v-else-if="item.score >= 10">良好</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view class="empty-tip" v-if="filteredScores.length === 0">
				<image src="/static/images/empty.png" mode="aspectFit"></image>
				<text>这一天没有分数记录哦~</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		globalVariable
	} from '../../configMy.js';
	export default {
		data() {
			return {
				teacher: {},
				currentStudent: {
					aver: '',
					grade: '',
					studentName: '',
					studentId: ''
				},
				activeDateIndex: 0,
				dateList: [],
				scoreList: [],
				touchStartX: 0,
				currentTranslateX: 0,
				activeIndex: -1,
				touchStates: {},
				activeSwipeId: null
			}
		},
		computed: {
			filteredScores() {
				if (this.dateList.length === 0) return [];
				const selectedDate = this.dateList[this.activeDateIndex];

				return this.scoreList.filter(item => {
					const itemDate = item.time.split(' ')[0];
					return itemDate === selectedDate;
				}).sort((a, b) => {
					return new Date(b.time) - new Date(a.time);
				}).map(item => {
					return {
						...item,
						translateX: item.translateX || 0,
						displayScore: item.role === 1 ? `+${item.score}` : `-${item.score}`
					}
				});
			},
			dailyTotalScores() {
				if (this.filteredScores.length === 0) return 0;
				return this.filteredScores.reduce((sum, item) => {
					return item.role === 1 ? sum + item.score : sum - item.score;
				}, 0);
			},
			dailySubjectCount() {
				if (this.filteredScores.length === 0) return 0;
				const subjects = new Set(this.filteredScores.map(item => item.scoreType).filter(Boolean));
				return subjects.size;
			},
			dailyMaxScoreItem() {
				if (this.filteredScores.length === 0) return {
					scoreName: '无',
					score: 0
				};
				return this.filteredScores.reduce((max, item) => {
					const currentScore = item.role === 1 ? item.score : -item.score;
					return currentScore > max.score ? {
						scoreName: item.scoreName,
						score: currentScore
					} : max;
				}, {
					scoreName: '',
					score: 0
				});
			}
		},
		onLoad(options) {
			this.currentStudent.studentId = options.studentId;
			let that = this;
			uni.getStorage({
				key: 'teacher',
				success(res) {
					that.teacher = res.data;
					that.fetchStudentScores();
				}
			})
		},
		methods: {
			getAvatarUrl(avatarUrl) {
				if (!avatarUrl || avatarUrl === 'null') {
					return '/static/aver1.jpg';
				}
				return globalVariable + '/get/' + avatarUrl;
			},
			fetchStudentScores() {
				uni.showLoading({
					title: '加载中...'
				});

				uni.request({
					url: `${globalVariable}/getScoresByStudentId?studentId=${this.currentStudent.studentId}`,
					success: (res) => {
						uni.hideLoading();
						let info = res.data;
						if (info.status == 1) {
							this.scoreList = info.data;
							if (this.scoreList.length > 0) {
								this.currentStudent = {
									aver: this.scoreList[0].aver,
									grade: this.scoreList[0].grade,
									studentName: this.scoreList[0].studentName,
									studentId: this.scoreList[0].studentId
								};
							}
							this.initDates();
						} else {
							uni.showToast({
								title: '暂无数据',
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: '加载失败',
							icon: 'none'
						});
						console.error('请求失败:', err);
					}
				});
			},
			getSubjectColor(subject) {
				if (!subject) return '#9E9E9E';
				const colors = {
					'英语': '#FF9A9E',
					'数学': '#667EEA',
					'语文': '#4CAF50',
					'物理': '#FF9800',
					'化学': '#9C27B0',
					'生物': '#009688',
					'历史': '#579652',
					'地理': '#963178'
				};
				return colors[subject] || '#607D8B';
			},
			getSubjectAbbr(subject) {
				if (!subject) return '系';
				return subject.substring(0, 1);
			},
			touchStart(e, id) {
				const item = this.scoreList.find(item => item.id === id);
				if (item.teacherId !== this.teacher.teacherId) return;
				if (this.activeSwipeId && this.activeSwipeId !== id) {
					this.$set(this.scoreList.find(item => item.id === this.activeSwipeId), 'translateX', 0);
				}

				this.activeSwipeId = id;
				this.touchStates[id] = {
					startX: e.touches[0].clientX,
					startTime: Date.now()
				};
			},
			touchMove(e, id) {
				const item = this.scoreList.find(item => item.id === id);
				if (item.teacherId !== this.teacher.teacherId) return;
				if (this.activeSwipeId !== id) return;

				const touchX = e.touches[0].clientX;
				const diffX = touchX - this.touchStates[id].startX;

				if (diffX > 0) {
					this.$set(this.scoreList.find(item => item.id === id), 'translateX', 0);
					return;
				}

				const maxLeft = -100;
				this.$set(this.scoreList.find(item => item.id === id), 'translateX', Math.max(diffX, maxLeft));
			},
			touchEnd(id) {
				const item = this.scoreList.find(item => item.id === id);
				if (item.teacherId !== this.teacher.teacherId) return;
				if (this.activeSwipeId !== id) return;

				const currentX = this.scoreList.find(item => item.id === id).translateX;
				const threshold = -50;
				const velocity = Math.abs(currentX) / (Date.now() - this.touchStates[id].startTime);

				if (currentX <= threshold || velocity > 0.3) {
					this.$set(this.scoreList.find(item => item.id === id), 'translateX', -80);
				} else {
					this.$set(this.scoreList.find(item => item.id === id), 'translateX', 0);
					this.activeSwipeId = null;
				}

				delete this.touchStates[id];
			},
			deleteScore(id) {
				uni.showModal({
					title: '提示',
					content: '确定要删除这条分数记录吗？',
					success: (res) => {
						if (res.confirm) {
							const url = `${globalVariable}/deleteScore?id=${id}`;

							uni.request({
								url: url,
								method: 'POST',
								success: (res) => {
									let info = res.data;
									if (info.status == 1) {
										this.scoreList = this.scoreList.filter(item => item.id !==
											id);
										uni.showToast({
											title: '删除成功',
											icon: 'success'
										});
										this.activeSwipeId = null;
									} else {
										uni.showToast({
											title: info.message || '删除失败',
											icon: 'none'
										});
									}
								},
								fail: (err) => {
									uni.showToast({
										title: '网络错误，删除失败',
										icon: 'none'
									});
									console.error('删除请求失败:', err);
								}
							});
						} else {
							this.$set(this.scoreList.find(item => item.id === id), 'translateX', 0);
							this.activeSwipeId = null;
						}
					}
				});
			},
			initDates() {
				const dates = this.scoreList.map(item => item.time.split(' ')[0]);
				const uniqueDates = [...new Set(dates)].sort((a, b) => new Date(b) - new Date(a));
				this.dateList = uniqueDates.slice(0, 30);

				if (this.dateList.length === 0) {
					const today = new Date();
					for (let i = 0; i < 7; i++) {
						const date = new Date();
						date.setDate(today.getDate() - i);
						const dateStr =
							`${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
						this.dateList.push(dateStr);
					}
				}
			},
			changeDate(index) {
				this.activeDateIndex = index;
			},
			formatDay(date) {
				if (!date) return '';
				const d = new Date(date.replace(/-/g, '/'));
				return d.getDate();
			},
			formatWeekday(date) {
				if (!date) return '';
				const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				const d = new Date(date.replace(/-/g, '/'));
				return weekdays[d.getDay()];
			},
			formatDate(date) {
				if (!date) return '';
				const d = new Date(date.replace(/-/g, '/'));
				return `${d.getMonth() + 1}月${d.getDate()}日`;
			},
			formatTime(time) {
				if (!time) return '';
				return time.split(' ')[1].substring(0, 5);
			}
		}
	}
</script>

<style lang="scss">
	.history-container {
		padding: 20rpx;
		min-height: 100vh;
		background: #f8f9fa;
	}

	/* 学生信息头部 */
	.student-header {
		display: flex;
		align-items: center;
		padding: 30rpx;
		margin-bottom: 30rpx;
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

		.student-avatar {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			border: 4rpx solid #fff;
			box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
			margin-right: 30rpx;
		}

		.student-info {
			display: flex;
			flex-direction: column;

			.student-name {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 10rpx;
			}

			.student-grade {
				font-size: 28rpx;
				color: #666;
				background: #f0f3f8;
				padding: 6rpx 16rpx;
				border-radius: 12rpx;
				align-self: flex-start;
			}
		}
	}

	/* 页面标题 */
	.header {
		margin-bottom: 40rpx;
		text-align: center;

		.title {
			display: block;
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 10rpx;
		}

		.subtitle {
			display: block;
			font-size: 26rpx;
			color: #888;
		}
	}

	/* 日期选择区域 */
	.date-scroll {
		white-space: nowrap;
		margin-bottom: 30rpx;
		padding: 10rpx 0;

		.date-cards {
			display: inline-flex;
			padding: 0 20rpx;
		}

		.date-card {
			display: inline-flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			width: 120rpx;
			height: 150rpx;
			margin-right: 20rpx;
			border-radius: 20rpx;
			background: #fff;
			box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.05);
			transition: all 0.3s ease;

			&.active {
				background: rgba(102, 126, 234, 0.1);
				box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.1);

				.day {
					color: #667EEA;
					font-weight: bold;
				}

				.weekday,
				.date {
					color: #667EEA;
				}
			}

			.day {
				font-size: 48rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 6rpx;
				transition: all 0.3s ease;
			}

			.weekday {
				font-size: 24rpx;
				color: #999;
				margin-bottom: 4rpx;
				transition: all 0.3s ease;
			}

			.date {
				font-size: 22rpx;
				color: #999;
				transition: all 0.3s ease;
			}
		}
	}

	/* 统计卡片 */
	.stats-container {
		margin-bottom: 30rpx;

		.stats-card {
			display: flex;
			justify-content: space-around;
			padding: 30rpx;
			background: #fff;
			border-radius: 20rpx;
			box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.05);

			.stat-item {
				display: flex;
				flex-direction: column;
				align-items: center;

				.stat-value {
					font-size: 36rpx;
					font-weight: bold;
					color: #667EEA;
					margin-bottom: 10rpx;
				}

				.stat-label {
					font-size: 24rpx;
					color: #666;
				}
			}
		}
	}

	/* 分数列表 */
	.score-list {
		.score-item-container {
			position: relative;
			margin-bottom: 20rpx;
			overflow: hidden;
			border-radius: 20rpx;
		}

		.delete-btn {
			position: absolute;
			right: 0;
			top: 0;
			bottom: 0;
			width: 100rpx;
			background-color: #ff5a5f;
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1;
		}

		.score-item {
			position: relative;
			z-index: 2;
			display: flex;
			padding: 30rpx;
			background: #fff;
			transition: transform 0.3s ease;

			&:active {
				transform: scale(0.98);
			}

			.subject-icon {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				color: white;
				font-size: 36rpx;
				font-weight: bold;
				margin-right: 20rpx;
				flex-shrink: 0;
			}

			.score-content {
				flex: 1;

				.score-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 10rpx;

					.score-name {
						font-size: 30rpx;
						font-weight: bold;
						color: #333;
						flex: 1;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
						margin-right: 20rpx;
					}

					.score-value {
						font-size: 36rpx;
						font-weight: bold;
						color: #FF9A9E;
					}
				}

				.score-detail {
					display: flex;
					justify-content: space-between;
					margin-bottom: 10rpx;

					.teacher-name {
						font-size: 26rpx;
						color: #666;
					}

					.time {
						font-size: 26rpx;
						color: #999;
					}
				}

				.score-footer {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.grade {
						font-size: 24rpx;
						color: #666;
						background: rgba(0, 0, 0, 0.05);
						padding: 4rpx 12rpx;
						border-radius: 20rpx;
					}

					.tags {
						.tag {
							font-size: 22rpx;
							color: #fff;
							background: linear-gradient(to right, #FF9A9E, #FAD0C4);
							padding: 4rpx 12rpx;
							border-radius: 20rpx;
							margin-left: 10rpx;
						}
					}
				}
			}
		}

		.empty-tip {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 60rpx 0;
			text-align: center;

			image {
				width: 200rpx;
				height: 200rpx;
				margin-bottom: 20rpx;
				opacity: 0.6;
			}

			text {
				font-size: 28rpx;
				color: #999;
			}
		}
	}

	.student-header-card {
		position: relative;
		margin-bottom: 20rpx;
		border-radius: 24rpx;
		overflow: hidden;
		background: linear-gradient(135deg, #d4a5f9, #69d5fc);
		box-shadow: 0 10rpx 30rpx rgba(102, 126, 234, 0.3);

		.header-content {
			display: flex;
			padding: 30rpx;
			position: relative;
			z-index: 2;
		}

		.student-avatar {
			width: 140rpx;
			height: 140rpx;
			border-radius: 50%;
			border: 4rpx solid rgba(255, 255, 255, 0.3);
			box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.15);
			margin-right: 30rpx;
			background: #fff;
		}

		.header-text {
			flex: 1;
			display: flex;
			flex-direction: column;
			justify-content: center;

			.student-name {
				font-size: 36rpx;
				font-weight: bold;
				color: #fff;
				margin-bottom: 8rpx;
				text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
			}

			.student-grade {
				font-size: 28rpx;
				color: rgba(255, 255, 255, 0.9);
				background: rgba(255, 255, 255, 0.2);
				padding: 4rpx 16rpx;
				border-radius: 20rpx;
				align-self: flex-start;
				margin-bottom: 20rpx;
			}

			.header-title {
				.title {
					display: block;
					font-size: 32rpx;
					font-weight: bold;
					color: #fff;
					margin-bottom: 4rpx;
				}

				.subtitle {
					display: block;
					font-size: 24rpx;
					color: rgba(255, 255, 255, 0.8);
				}
			}
		}

		.header-decoration {
			position: absolute;
			bottom: 0;
			right: 0;
			width: 200rpx;
			height: 200rpx;
			background: radial-gradient(circle at 70% 70%, rgba(255, 255, 255, 0.15) 0%, transparent 70%);
			z-index: 1;
		}
	}
</style>